import os
import cv2
import numpy as np
from colorFind import *
from circleFind import *


# 获取红色点外接矩形的旋转角度
def get_red_point_theta(_img):
    _contour, _mask = get_color_contour(_img, 'red', False)
    cv2.imwrite("red_mask.jpg", _mask)
    _mask_points = []
    _h, _w = get_HW(_mask)
    for i in range(_h):
        for j in range(_w):
            if _mask[i, j] != 0:
                _mask_points.append([i, j])
    _mask_points_np = np.array(_mask_points)
    ((_cx, _cy), (_width, _height), _theta) = cv2.minAreaRect(_mask_points_np)
    return int(_theta)


# 获取所需距离和角度
def get_distance_theta(_img, _bias=10):
    _cx, _cy, _cr = get_card_center_point(_img)
    _whiteboard_x, _whiteboard_y = get_whiteboard_center_point(_img)
    _red_lx, _red_ry, _red_rx, _red_ly = _cx - _cr, _cy + _cr, _cx + _cr, _cy - _cr
    _circle_img = _img[_red_ly - _bias:_red_ry + _bias, _red_lx - _bias:_red_rx + _bias]
    cv2.imwrite("res.jpg", _img)
    cv2.imwrite("circle_img.jpg", _circle_img)
    _theta = get_red_point_theta(_circle_img)
    return (_cx - _whiteboard_x) ** 2 + (_cy - _whiteboard_y) ** 2, _theta


def is_move(_base_img_path, _judge_img_path, _threshold_distance=10000, _threshold_theta=20):
    _ret = False
    _base_img = to_resize(cv2.imread(_base_img_path), 4)
    _base_distance, _base_theta = get_distance_theta(_base_img)
    _judge_img = to_resize(cv2.imread(_judge_img_path), 4)
    _distance, _theta = get_distance_theta(_judge_img)
    _error_dis = abs(_base_distance - _distance)
    _error_theta = abs(_base_theta - _theta)
    print("error distance:", _error_dis)
    print("error theta:", _error_theta)
    if _error_dis > _threshold_distance or _error_theta > _threshold_theta:
        print("发现移动")
        _ret = True
    else:
        print("未发现移动")
    cv2.imshow("img", _judge_img)
    return _ret


if __name__ == '__main__':
    base_img_path = r"E:\BaiduDisk\500\IMG_20210918_234858.jpg"
    base_img = to_resize(cv2.imread(base_img_path), 4)
    cv2.imshow("base img", base_img)
    root = r"E:\BaiduDisk\500"
    names = os.listdir(root)
    for name in names:
        img_path = r"E:\BaiduDisk\500\\" + name
        is_move(base_img_path, img_path)
        cv2.waitKey(0)
    cv2.destroyAllWindows()
